const Product = require('../models/Product');

// 获取所有商品（支持分页和条件查询）
const getAllProductsService = async (params) => {
    try {
        const where = {};
        let page = 1;
        let pageSize = 10;

        if (params) {
            if (params.name) {
                where.name = params.name;
            }
            if (params.category) {
                where.category_id = params.category;
            }
            if (params.status) {
                where.status = params.status;
            }
            if (params.page) {
                page = parseInt(params.page, 10);
            }
            if (params.pageSize) {
                pageSize = parseInt(params.pageSize, 10);
            }
        }

        const offset = (page - 1) * pageSize;
        const limit = pageSize;

        const { count, rows } = await Product.findAndCountAll({
            where: where,
            attributes: [
                'id',
                'name',
                'category_id',
                'description',
                'image_url',
                'banner_image_urls',
                'rent_price_day',
                'deposit',
                'min_rent_days',
                'max_rent_days',
                'specifications',
                'status',
                'view_num',
                'is_recommend',
                'rent_date',
                'created_at',
                'updated_at'
            ],
            offset: offset,
            limit: limit,
            order: [['id', 'DESC']]
        });

        return {
            total: count,
            list: rows,
            page: page,
            pageSize: pageSize
        };
    } catch (err) {
        throw new Error(`Error in getAllProductsService: ${err.message}`);
    }
};
// 前台商品列表
const searchProduct = async (params) => {
    try {
        const where = { status: 1 };
        const order = [];
        let page = 1;
        let pageSize = 10;

        if (params) {
            if (params.name) {
                //如果name存在的话，用name字段使用模糊查询
                where.name = {
                    [db.Sequelize.Op.like]: `%${params.name}%`
                };
            }
            if (params.category_id) {
                where.category_id = params.category_id;
            }
            if (params.page) {
                page = parseInt(params.page, 10);
            }
            if (params.pageSize) {
                pageSize = parseInt(params.pageSize, 10);
            }

            if (params.type) {

                switch (params.type) {
                    case 1:
                        //推荐商品
                        where.is_recommend = 1;
                        break;
                    case 2:
                        //热门商品，view_num降序排列
                        order.push(['view_num', 'DESC']);
                        break;
                    case 3:
                        //最新商品，created_at降序排列
                        order.push(['created_at', 'DESC']);
                        break;
                }

            }
        }

        const offset = (page - 1) * pageSize;
        const limit = pageSize;
        order.push(['id', 'DESC']);

        const { count, rows } = await Product.findAndCountAll({
            where: where,
            attributes: [
                'id',
                'name',
                'category_id',
                'description',
                'image_url',
                'banner_image_urls',
                'rent_price_day',
                'deposit',
                'min_rent_days',
                'max_rent_days',
                'specifications',
                'status',
                'view_num',
                'is_recommend',
                'rent_date',
                'created_at',
                'updated_at'
            ],
            offset: offset,
            limit: limit,
            order: order
        });

        return {
            total: count,
            list: rows,
            page: page,
            pageSize: pageSize
        };
    } catch (err) {
        throw new Error(`Error in getAllProductsService: ${err.message}`);
    }
}


// 根据 ID 查询单个商品信息
const getProductById = async (productId) => {
    try {
        const product = await Product.findByPk(productId, {
            attributes: [
                'id',
                'name',
                'category_id',
                'description',
                'image_url',
                'banner_image_urls',
                'rent_price_day',
                'deposit',
                'min_rent_days',
                'max_rent_days',
                'specifications',
                'status',
                'view_num',
                'is_recommend',
                'rent_date',
                'created_at',
                'updated_at'
            ],
        });
        if (!product) {
            console.log('Product not found');
            throw new Error('Product not found');
        }
        return product;
    } catch (err) {
        throw err;
    }
};

// 新增商品
const addProduct = async (productData) => {
    try {
        const newProduct = await Product.create(productData);
        return newProduct;
    } catch (err) {
        throw new Error(`Error in addProduct: ${err.message}`);
    }
};

// 更新商品信息
const updateProduct = async (productId, productData) => {
    try {
        const existingProduct = await Product.findByPk(productId);
        if (!existingProduct) {
            throw new Error('Product not found');
        }
        await existingProduct.update(productData);
        return existingProduct;
    } catch (err) {
        throw new Error(`Error in updateProduct: ${err.message}`);
    }
};

// 删除商品
const deleteProductService = async (productId) => {
    try {
        const existingProduct = await Product.findByPk(productId);
        if (!existingProduct) {
            throw new Error('Product not found');
        }
        await existingProduct.destroy();
        return true;
    } catch (err) {
        throw new Error(`Error in deleteProduct: ${err.message}`);
    }
};

module.exports = {
    getAllProductsService,
    getProductById,
    addProduct,
    updateProduct,
    deleteProductService,
    searchProduct
};
